<template>
    <el-dialog :visible.sync="showAddModal" :append-to-body="true"
               :close-on-click-modal="false" width="60%"
               :close-on-press-escape="false" :show-close="false" class="add-product-modal">
        <h4 slot="title">{{modalLabel}}</h4>
        <el-form :model="newForm" class="demo-form-inline" :modal-append-to-body='false' :rules="rules" ref="ruleForm">
            <div>
                <h3 class="panel-title">基本信息 </h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="名称" :label-width="formLabelWidth" prop="goodsName">
                        <el-input v-model="newForm.goodsName" auto-complete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="分类" :label-width="formLabelWidth" prop="categoryId">
                        <el-select v-model="newForm.categoryId" placeholder="请选择分类" clearable>
                            <el-option
                                v-for="item in categoryList"
                                :key="item.categoryId"
                                :label="item.categoryName"
                                :value="item.categoryId">
                                <span style="float: left">{{ item.categoryName }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="单位" :label-width="formLabelWidth" prop="specsId">
                        <el-select v-model="newForm.specsId " placeholder="请选择单位" clearable>
                            <el-option
                                v-for="item in specsList"
                                :key="item.id"
                                :label="item.specsName"
                                :value="item.id">
                                <span style="float: left">{{ item.specsName }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="商品图片" :label-width="formLabelWidth" prop="picUrl">
                <template v-if="$isEmptyArray(newForm.goodsPicList)">
                    <el-upload ref="upload" name="upFile"
                               :class="{'ele-upload':disableUpload}"
                               :action="getUploadUrl()"
                               list-type="picture-card"
                               :limit="5"
                               :multiple="true"
                               accept="image/png,image/gif,image/jpeg,image/jpg"
                               :auto-upload="true"
                               :before-upload="beforeUpload"
                               :on-preview="handlePictureCardPreview"
                               :on-change="handleChange"
                               :on-remove="handleRemove"
                               :file-list="fileList">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible" size="tiny" :append-to-body="true">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                    <span v-if="disableUpload" style="color: #ea394c;font-size: 12px;">
                         <i class="el-icon-warning"></i>
                         最多只允许上传5张图片!
                     </span>
                </template>
                <template v-else>
                    <ul class="bill-tips clearfix" v-if="!$isEmptyArray(newForm.goodsPicList)">
                        <li style="width: 15%;" v-for="item in newForm.goodsPicList">
                            <img style="height: 80px;width: 80px;margin-bottom: 6px;margin-top: 6px;float: left;"
                                 :src="item.pic">
                        </li>
                    </ul>
                </template>
            </el-form-item>
            <div>
                <h3 class="panel-title">商品属性
                    <span class="title-tips" style="font-size: 12px;color: #999">没有合适的属性？快去&nbsp;&nbsp;
                        <a href="javascript:;">商品信息──>商品属性维护</a>&nbsp;&nbsp;
                    页面设置吧</span>
                </h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="型号" :label-width="formLabelWidth" prop="property.model">
                        <el-input v-model="newForm.property.model" auto-complete="off" placeholder="型号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="品牌" :label-width="formLabelWidth" prop="property.brand">
                        <el-input v-model="newForm.property.brand" auto-complete="off" placeholder="品牌"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="颜色" :label-width="formLabelWidth" prop="color">
                        <el-input v-model="newForm.property.color" auto-complete="off" placeholder="颜色"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="规格" :label-width="formLabelWidth">
                        <el-input v-model="newForm.property.specifications" auto-complete="off"
                                  placeholder="规格"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="存储条件" :label-width="formLabelWidth" prop="storageCondition">
                        <el-input v-model="newForm.property.storageCondition" auto-complete="off"
                                  placeholder="存储条件"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div>
                <h3 class="panel-title">附加信息 </h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="生产商" :label-width="formLabelWidth" prop="manuFacturer">
                        <el-input v-model="newForm.property.manuFacturer" auto-complete="off"
                                  placeholder="生产商"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="保质期" :label-width="formLabelWidth">
                        <el-input v-model="newForm.property.qualityGuaranteePeriod" auto-complete="off"
                                  placeholder="保质期"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="生产日期" :label-width="formLabelWidth" prop="manuFactureDate">
                        <!--                        <el-input v-model="newForm.manuFactureDate" auto-complete="off" placeholder="生产日期"></el-input>-->
                        <el-date-picker type="datetime" placeholder="选择日期" v-model="newForm.property.manuFactureDate"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="出产地" :label-width="formLabelWidth" prop="provinceId">
                        <el-cascader clearable
                                     size="large"
                                     :options="options"
                                     v-model="selectedOptions"
                                     @change="handleProvinceChange" style="width: 100%">
                        </el-cascader>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="所在街道/村落" :label-width="formLabelWidth" prop="address">
                        <el-input
                            type="textarea"
                            :rows="2"
                            resize="none"
                            placeholder="请输入内容"
                            v-model="newForm.property.address">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="注意事项" :label-width="formLabelWidth" prop="attention">
                        <el-input
                            type="textarea"
                            :rows="2"
                            resize="none"
                            placeholder="请输入内容"
                            v-model="newForm.property.attention">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="说明" :label-width="formLabelWidth" prop="information">
                        <el-input
                            type="textarea"
                            :rows="2"
                            resize="none"
                            placeholder="请输入内容"
                            v-model="newForm.property.information">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div>
                <h3 class="panel-title">价格信息</h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="零售价格" :label-width="formLabelWidth" prop="price">
                        <el-input v-model="newForm.price" auto-complete="off" placeholder="零售价格"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="促销价格" :label-width="formLabelWidth" prop="promotionPrice">
                        <el-input v-model="newForm.promotionPrice" auto-complete="off" placeholder="促销价格"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div>
                <h3 class="panel-title">库存信息</h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="库存数量" :label-width="formLabelWidth" prop="stock">
                        <el-input v-model="newForm.stock" auto-complete="off" placeholder="库存数量"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <div>
                <h3 class="panel-title">其他信息 </h3>
            </div>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="展出状态" :label-width="formLabelWidth" prop="status">
                        <el-radio-group v-model="newForm.status">
                            <el-radio :label="1">上架</el-radio>
                            <el-radio :label="0">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="促销状态" :label-width="formLabelWidth" prop="isRecommend">
                        <el-radio-group v-model="newForm.isRecommend">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                        <el-input
                            type="textarea"
                            :rows="2"
                            resize="none"
                            placeholder=""
                            v-model="newForm.remark">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="描述" :label-width="formLabelWidth" class="ele-editor">
                        <ele-editor v-model="newForm.describe"></ele-editor>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="row" style="text-align: center">
            <a class="revision-btn" href="javaScript:void(0)" @click="onSubmit">保 存</a>
            <a class="revision-btn-default" style="margin-left: 5px;" href="javaScript:void(0)" @click="onCancel">取
                消</a>
        </div>
    </el-dialog>
</template>

<script>

    import {CodeToText, regionData} from 'element-china-area-data';
    import EleEditor from "../../components/eleEditor.vue";

    export default {
        name: "addProductModal",
        components: {EleEditor},
        props: {
            showAddModal: {
                type: Boolean,
                default: false
            },
            goodsId: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                modalLabel: '新增商品',
                newForm: {
                    goodsId: 0,
                    goodsName: '',
                    categoryId: '',
                    specsId: '',
                    picUrl: '',
                    price: '',
                    promotionPrice: '',
                    stock: '',
                    status: 1,
                    isRecommend: 0,
                    remark: '',
                    goodsPicList: [],
                    describe: '',
                    property: {
                        model: '',
                        brand: '',
                        color: '',
                        specifications: '',
                        storageCondition: '',
                        manuFacturer: '',
                        qualityGuaranteePeriod: '',
                        manuFactureDate: '',
                        provinceId: '',
                        provinceName: '',
                        cityId: '',
                        cityName: '',
                        districtId: '',
                        districtName: '',
                        address: '',
                        attention: '',
                        information: '',
                    }
                },
                rules: {
                    goodsName: [
                        {required: true, message: '请输入名称', trigger: 'blur'}
                    ],
                    categoryId: [
                        {required: true, message: '请选择分类', trigger: 'change'}
                    ],
                    specsId: [
                        {required: true, message: '请选择单位', trigger: 'change'}
                    ],
                    // 'property.model': [
                    //     {required: true, message: '请输入型号', trigger: 'blur'}
                    // ],
                    // 'property.brand': [
                    //     {required: true, message: '请输入品牌', trigger: 'blur'}
                    // ],
                    price: [
                        {required: true, message: '请输入零售价格', trigger: 'blur'}
                    ],
                    stock: [
                        {required: true, message: '请输入库存数量', trigger: 'blur'}
                    ],
                },
                formLabelWidth: '100px',
                dialogImageUrl: '',
                dialogVisible: false,
                fileList: [],
                uploadFiles: [],
                uploadFile: {},
                uploadUrl: '/sys/oss/upload',
                formData: {},
                uploadedFiles: [],
                disableUpload: false,
                uploadedFileMap: new Map(),
                categoryList: [],
                specsList: [],
                options: regionData,
                selectedOptions: [],
            }
        },
        mounted: function () {
            this.listAllCategory();
            this.listAllSpecies();
        },
        methods: {
            handleProvinceChange(value) {
                for (let i = 0; i < value.length; i++) {
                    if (i === 0) {
                        this.newForm.property.provinceId = value[i];
                        this.newForm.property.provinceName = CodeToText[value[i]];
                    }
                    if (i === 1) {
                        this.newForm.property.cityId = value[i];
                        this.newForm.property.cityName = CodeToText[value[i]];
                    }
                    if (i === 2) {
                        this.newForm.property.districtId = value[i];
                        this.newForm.property.districtName = CodeToText[value[i]];
                    }
                }
            },
            onCancel() {
                this.$refs.ruleForm.resetFields();
                this.newForm = this.$options.data().newForm;
                this.selectedOptions = [];
                this.initUploadCfg();
                this.$emit('onCancelNewModal');
            },
            onSubmit() {

                if (this.$isEmptyStr(this.goodsId) && this.$isEmptyArray(this.uploadedFiles)) {
                    this.$message.warning('请上传商品图片');
                    return;
                }
                if (!this.$isEmptyArray(this.uploadedFiles)) {
                    let picObjArr = [];
                    for (let picUrl of this.uploadedFiles) {
                        let picObj = {
                            pic: picUrl
                        }
                        picObjArr.push(picObj);
                        this.newForm.goodsPicList = picObjArr;
                    }
                }
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        if (this.$isEmptyStr(this.goodsId)) {
                            this.submitNewInfo();
                        } else {
                            this.submitEditInfo();
                        }
                    } else {
                        return false;
                    }
                });

            },
            async listAllCategory() {
                let res = await this.$api.get('/mall/category/getAll', {});
                if (res.code === 0) {
                    this.categoryList = res.categoryList;
                } else {
                    this.$message.error(res.msg);
                }
            },
            async listAllSpecies() {
                let res = await this.$api.get('/mall/goodsspecs/getAll', {});
                if (res.code === 0) {
                    this.specsList = res.specsList;
                } else {
                    this.$message.error(res.msg);
                }
            },
            async submitEditInfo() {
                let res = await this.$api.post('/mall/goods/update', this.newForm);
                if (res.code === 0) {
                    this.initUploadCfg();
                    this.$refs.ruleForm.resetFields();
                    this.newForm = this.$options.data().newForm;
                    this.selectedOptions = [];
                    this.$message.success('保存成功');
                    this.$emit('onSubmitNewModal');
                } else {
                    this.$message.error(res.msg);
                }
            },
            async submitNewInfo() {
                var userId = this.$getCookie('userId')
                this.newForm.userId = userId
                let res = await this.$api.post('/mall/goods/save', this.newForm);
                if (res.code === 0) {
                    this.initUploadCfg();
                    this.$refs.ruleForm.resetFields();
                    this.newForm = this.$options.data().newForm;
                    this.selectedOptions = [];
                    this.$message.success('保存成功');
                    this.$emit('onSubmitNewModal');
                } else {
                    this.$message.error(res.msg);
                }
            },
            async getInfo(id) {
                let res = await this.$api.get('/mall/goods/info/' + id, {});
                if (res.code === 0) {
                    this.newForm.goodsId = res.goods.goodsId;
                    this.newForm.goodsName = res.goods.goodsName;
                    this.newForm.categoryId = res.goods.categoryId;
                    this.newForm.specsId = res.goods.specsId;
                    this.newForm.picUrl = res.goods.picUrl;
                    this.newForm.price = res.goods.price;
                    this.newForm.promotionPrice = res.goods.promotionPrice;
                    this.newForm.stock = res.goods.stock;
                    this.newForm.status = res.goods.status;
                    this.newForm.isRecommend = res.goods.isRecommend;
                    this.newForm.remark = res.goods.remark;
                    this.newForm.describe = res.goods.describe;
                    if (!this.$isEmptyArray(res.goods.goodsPicList)) {
                        this.newForm.goodsPicList = res.goods.goodsPicList;
                    }
                    if (!this.$isNullObj(res.goods.property)) {
                        this.newForm.property = res.goods.property;
                        let locations = [];
                        if (!this.$isEmptyStr(res.goods.property.provinceId)) {
                            locations.push(String(res.goods.property.provinceId))
                        }
                        if (!this.$isEmptyStr(res.goods.property.cityId)) {
                            locations.push(String(res.goods.property.cityId))
                        }
                        if (!this.$isEmptyStr(res.goods.property.districtId)) {
                            locations.push(String(res.goods.property.districtId))
                        }
                        this.selectedOptions = locations;
                    }
                } else {
                    this.$message.error(res.msg);
                }
            },
            /* ******** File Upload config start ******** */
            getUploadUrl() {
                return '/api/sys/oss/upload';
            },
            initUploadCfg() {
                this.uploadedFiles.length = 0;
                this.uploadedFileMap.clear();
                this.disableUpload = false;
                this.newForm.goodsPicList.length = 0;
            },
            handleRemove(file, fileList) {
                this.uploadedFileMap.delete(file.uid);
                this.uploadedFiles.pop();
                if (fileList.length < 5) {
                    this.disableUpload = false;
                }
            },
            handleChange(file, fileList) {
                this.uploadedFileMap.set(file.uid, file.url);
                if (fileList.length === 5) {
                    this.disableUpload = true;
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            beforeUpload(file) {
                this.formData = new FormData();
                this.formData.append('file', file);
                this.submitUpload();

            },
            async submitUpload() {
                let res = await this.$api.post(this.uploadUrl, this.formData);
                if (res.code === 0) {
                    this.uploadedFiles.push(res.url);
                } else {
                    this.$message.error(res.msg);
                }
            },
            /* ******** File Upload config end ******** */
        }
    }
</script>

<style scoped>
    .add-product-modal /deep/ .el-form-item__label {
        font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 12px;
        color: #676a6c;
    }

    .add-product-modal /deep/ .el-radio__label {
        font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        font-size: 12px;
        color: #676a6c;
        font-weight: normal;
    }

    .add-product-modal /deep/ .el-select {
        display: inline;
    }

    /deep/ .el-upload__input {
        display: none;
    }

    /deep/ .el-dialog__wrapper {
        z-index: 3000;
    }

    .add-product-modal /deep/ .el-dialog__header {
        border-bottom: 1px solid #e5e5e5;
        padding: 5px 0 2px 15px !important;
    }

    .add-product-modal /deep/ .el-dialog__body {
        padding: 0 20px 20px 20px;
    }

    .add-product-modal /deep/ .el-dialog__footer {
        border-top: 1px solid #e5e5e5;
        padding: 15px;
    }

    /* ******** File Upload config start ******** */
    .ele-upload /deep/ .el-upload--picture-card {
        display: none;
    }

    .ele-upload-item /deep/ .el-form-item__content {
        line-height: 0;
    }

    /* ******** File Upload config end ******** */
    .ele-editor /deep/ .el-form-item__content {
        line-height: normal;
    }
</style>
